import logging
from typing import Dict, List, Optional, Type
from datetime import datetime
from .dragon_repair import DragonRepairStrategy
from src.stock.stock_manager import StockManager
import pandas as pd

logger = logging.getLogger(__name__)

class StrategyManager:
    """策略管理器，负责所有策略的初始化、运行和结果汇总"""
    
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance
        
    def __init__(self):
        if not self._initialized:
            # 获取股票管理器实例
            self.stock_manager = StockManager.get_instance()
            # 注册所有策略
            self.strategies = {
                'dragon_repair': DragonRepairStrategy
            }
            # 策略实例字典
            self.strategy_instances = {}
            self._initialized = True
    
    def get_normal_stocks(self) -> List[Dict]:
        """获取普通股票列表的统一接口"""
        try:
            return self.stock_manager.data_processor.normal_stocks
        except Exception as e:
            logger.error(f"获取普通股票列表失败: {str(e)}")
            return []

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance
    
    def initialize_strategy(self, strategy_name: str) -> bool:
        """初始化指定策略"""
        try:
            if strategy_name not in self.strategies:
                logger.error(f"策略 {strategy_name} 不存在")
                return False
                
            if strategy_name not in self.strategy_instances:
                strategy_class = self.strategies[strategy_name]
                self.strategy_instances[strategy_name] = strategy_class(self)
                logger.info(f"策略 {strategy_name} 初始化成功")
                
            return True
        except Exception as e:
            logger.error(f"初始化策略 {strategy_name} 失败: {str(e)}")
            return False
    
    def run_strategy(self, strategy_name: str) -> List[Dict]:
        """运行指定策略"""
        try:
            if strategy_name not in self.strategy_instances:
                if not self.initialize_strategy(strategy_name):
                    return []
            
            strategy = self.strategy_instances[strategy_name]
            results = strategy.run()
            
            logger.info(f"策略 {strategy_name} 选出 {len(results)} 只股票")
            return results
        except Exception as e:
            logger.error(f"运行策略 {strategy_name} 失败: {str(e)}")
            return []
    
    def run_all_strategies(self) -> Dict[str, List[Dict]]:
        """运行所有策略"""
        try:
            results = {}
            for strategy_name in self.strategies:
                results[strategy_name] = self.run_strategy(strategy_name)
                
            logger.info(f"所有策略运行完成,共 {len(results)} 个策略")
            return results
        except Exception as e:
            logger.error(f"运行所有策略失败: {str(e)}")
            return {}
    
    def get_strategy_list(self) -> List[str]:
        """获取所有可用策略列表"""
        return list(self.strategies.keys())
